package com.fxp.project.jiuselu.web.models.user.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fxp.project.jiuselu.commons.constant.ConstantCode;
import com.fxp.project.jiuselu.commons.exceptions.JiuLuException;
import com.fxp.project.jiuselu.web.business.v1.pojo.UserInfoVo;
import com.fxp.project.jiuselu.web.domain.CommonResult;
import com.fxp.project.jiuselu.web.models.user.entity.JslPcUserOauth;
import com.fxp.project.jiuselu.web.models.user.entity.JslUserOauth;
import com.fxp.project.jiuselu.web.models.user.mapper.JslPcUserOauthMapper;
import com.fxp.project.jiuselu.web.models.user.mapper.JslUserMapper;
import com.fxp.project.jiuselu.web.models.user.mapper.JslUserOauthMapper;
import com.fxp.project.jiuselu.web.models.user.request.Accesstoken;
import com.fxp.project.jiuselu.web.models.user.request.WxuserInfo;
import com.fxp.project.jiuselu.web.models.user.service.IJslUserOauthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 三方平台认证信息 服务实现类
 * </p>
 *
 * @author Jason.Wang
 * @since 2021-12-26
 */
@Service
public class JslUserOauthServiceImpl extends ServiceImpl<JslUserOauthMapper, JslUserOauth> implements IJslUserOauthService {

    @Autowired
    private JslUserMapper userMapper;
    @Autowired
    private JslPcUserOauthMapper jslPcUserOauthMapper;

    public static final String OPEN_WEB_URL="https://open.weixin.qq.com/connect/qrconnect?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_login&state=%s&connect_redirect=1&connect_redirect=1#wechat_redirect";
    public static final String WECHAT_APPID="wx9c648e3ccff311a7";
    public static final String WECHAT_SECRET="69759236ea6ab0b091d545470f75336b";
    @Override
    public String getQRcode() {
        String redirctUrl="https://www.shop.9cddc.com";
        String url= "";
        try {
            Long time=System.currentTimeMillis();
            String state=time +"314";
            String backUrl= URLEncoder.encode(redirctUrl,"GBK");
            url=String.format(OPEN_WEB_URL,WECHAT_APPID,backUrl,state);
            System.out.println(url);
        }catch (Exception e){
            throw new JiuLuException(ConstantCode.SYSTEM_EXCEPTION.getCode(), "获取二维码异常");
        }
        return url;
    }

    @Override
    public WxuserInfo wxLogin(HttpServletRequest request, HttpServletResponse response,String code,Integer oauth,Integer state) {
        String code1=request.getParameter("code");
        Accesstoken accesstoken=new Accesstoken();
//        if(code ==null){
//            throw new JiuLuException(ConstantCode.PARAM_EXCEPTION.getCode(),"用户拒绝授权");
//        }
            String getAccessTokenUrl="https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code&connect_redirect=1";
            getAccessTokenUrl=getAccessTokenUrl.replaceAll("APPID",WECHAT_APPID);
            getAccessTokenUrl=getAccessTokenUrl.replaceAll("SECRET",WECHAT_SECRET);
            getAccessTokenUrl=getAccessTokenUrl.replaceAll("CODE",code1);
            System.out.println(getAccessTokenUrl);
            String accessTokenStr = HttpUtil.get(getAccessTokenUrl);
            if(accessTokenStr.contains("40029")){
                throw new JiuLuException(ConstantCode.SYSTEM_EXCEPTION.getCode(),"无效的code");
            }else if(accessTokenStr.contains("40163")){
                throw new JiuLuException(ConstantCode.SYSTEM_EXCEPTION.getCode(),"code已经被使用");
            }
            if(!accessTokenStr.isEmpty()){
                accesstoken = JSONUtil.toBean(accessTokenStr,Accesstoken.class);
            }
        System.out.println(accesstoken);
        WxuserInfo wxuserInfo = this.getuserInfo(accesstoken.getAccess_token(), accesstoken.getOpenid(),oauth,state);
        return wxuserInfo;
    }

    /**
     *
     * @param oauth 0用户扫码1代理扫码
     * @param state 0微信登录1微信绑定
     */
    @Override
    public WxuserInfo getuserInfo(String accessToken, String openId,Integer oauth,Integer state) {
        WxuserInfo wxuserInfo=new WxuserInfo();
        String userUrl="https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&connect_redirect=1&lang=zh_CN";
        userUrl=userUrl.replaceAll("ACCESS_TOKEN",accessToken);
        userUrl=userUrl.replaceAll("OPENID",openId);
        System.out.println(userUrl);
        System.out.println(openId);
        String wxuserInfoUrl = HttpUtil.get(userUrl);
        if(wxuserInfoUrl.contains("errcode")){
            throw new JiuLuException(ConstantCode.SYSTEM_EXCEPTION.getCode(), "获取用户信息异常");
        }
        wxuserInfo =JSONUtil.toBean(wxuserInfoUrl,WxuserInfo.class);
        openId=wxuserInfo.getOpenid();
        System.out.println(wxuserInfo.getOpenid());
        JslPcUserOauth jslPcUserOauth = jslPcUserOauthMapper.selectPcUserOauthByOpenId(openId);
        if(state==0){
            if(jslPcUserOauth==null){
                throw new JiuLuException(ConstantCode.CHECK_WXUSER_MES_NULL.getCode(),wxuserInfo.getOpenid());
            }else {
                Long userId = jslPcUserOauth.getUserId();
                UserInfoVo userInfoVoByUserId = userMapper.getUserInfoVoByUserId(userId);
                if(userInfoVoByUserId.getEnable()==0) throw new JiuLuException(ConstantCode.PARAM_EXCEPTION.getCode(),"系统识别该账号异常，如有疑问请联系客服400-8388-326");
                wxuserInfo.setPhone(userInfoVoByUserId.getUserPhone());
            }
        }else {
            if(jslPcUserOauth==null){
//                JslUserOauth userOauth=new JslUserOauth();
//                userOauth.setOpenid(openId);
//                userOauth.setOauth(oauth.toString());
//                userOauth.setOauthType(3);
//                jslUserOauthMapper.insert(userOauth);
                JslPcUserOauth pcUserOauth=new JslPcUserOauth();
                pcUserOauth.setOpenId(openId);
                pcUserOauth.setCreateTime(LocalDateTime.now());
                jslPcUserOauthMapper.insert(pcUserOauth);
                wxuserInfo.setOpenid(openId);
            }else {
                wxuserInfo.setOpenid(openId);
            }
        }

        System.out.println(wxuserInfo);
        return wxuserInfo;
    }

    /**
     * pc微信绑定
     * @return
     */
    @Override
    public int bundlingWx(String openId,Long userId){
//        JslUserOauth userOauth =new JslUserOauth();
        JslPcUserOauth pcUserOauth=new JslPcUserOauth();
//        JslUserOauth oauth = jslUserOauthMapper.sel
//        ectOne(new QueryWrapper<JslUserOauth>().eq("openid", openId).eq("oauth_type",3));
        JslPcUserOauth oauth = jslPcUserOauthMapper.selectOne(new QueryWrapper<JslPcUserOauth>().eq("open_id", openId));
        if(oauth !=null){
            System.out.println("oauth !=null");
            System.out.println(userId);
            System.out.println(openId);
//            int i = jslUserOauthMapper.updateUserIdByOpenId(userId,openId);
            int i = jslPcUserOauthMapper.updateUserIdByOpenId(userId, openId);
            System.out.println(i);
            if(i==0) return 0;
        }
//        JslUserOauth userOauth1 = jslUserOauthMapper.selectOne(new QueryWrapper<JslUserOauth>().eq("user_id", userId).eq("oauth_type",3));
        JslPcUserOauth pcUserOauth1 = jslPcUserOauthMapper.selectOne(new QueryWrapper<JslPcUserOauth>().eq("user_id", userId));
        if(pcUserOauth1==null){
            System.out.println("userOauth1==null");
            pcUserOauth.setUserId(userId);
            pcUserOauth.setOpenId(openId);
            pcUserOauth.setCreateTime(LocalDateTime.now());
//            int insert = jslUserOauthMapper.insert(pcUserOauth);
            int insert = jslPcUserOauthMapper.insert(pcUserOauth);
            if(insert==0) return 0;
        }
        return 1;
    }

    @Override
    public int endBind(Long userId) {
        JslPcUserOauth pcUserOauth = jslPcUserOauthMapper.selectOne(new QueryWrapper<JslPcUserOauth>().eq("user_id", userId));
        if(pcUserOauth==null){
            return 0;
        }
        return jslPcUserOauthMapper.deletePcUserOauthByOpenId(userId);
    }
}
